package cn.tedu.straw.portal.controller;


import cn.tedu.straw.portal.dto.PostQuestionDTO;
import cn.tedu.straw.portal.ex.*;
import cn.tedu.straw.portal.model.Question;
import cn.tedu.straw.portal.security.LoginUserInfo;
import cn.tedu.straw.portal.service.IQuestionService;
import cn.tedu.straw.portal.util.Result;
import cn.tedu.straw.portal.vo.QuestionSimpleListItemVO;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2020-11-12
 */
@RestController
@RequestMapping("/portal/questions")
public class QuestionController {
    @Autowired
    IQuestionService questionService;

    @Value("${project.fileupload.question-image.base-dir}")
    String uploadBaseDir;

    @Value("${project.fileupload.question-image.max-size}")
    Long uploadMaxSize;

    @Value("${project-fileupload.question-image.content-types}")
    List<String> contentTypes;
    @RequestMapping("/post")
    public Result post(@Valid PostQuestionDTO postQuestionDTO, BindingResult bindingResult,
                       @AuthenticationPrincipal LoginUserInfo loginUserInfo){
        if(bindingResult.hasErrors()){
            String errorMessage=bindingResult.getFieldError().getDefaultMessage();
            throw new ParamValidationException(errorMessage);
        }

        Integer userId = loginUserInfo.getId();
        String userNickName = loginUserInfo.getNickName();
        questionService.post(postQuestionDTO, userId, userNickName);
        return Result.ok();
    }

    @PostMapping("/upload-image")
    public Result uploadimage(MultipartFile imageFile){
        if(imageFile.isEmpty()){
            throw  new FileEmptyException("上传图片失败！请选择有效的文件");
        }
        if(uploadMaxSize<imageFile.getSize()){
            throw new FileSizeException("上传图片失败！不允许上传超过"+uploadMaxSize/1024+"kb的文件");
        }
        if(!contentTypes.contains(imageFile.getContentType())){
            throw new FileTypeException("上传图片失败，允许上传的图片类型有："+contentTypes);
        }
        String yearAndMonth = DateTimeFormatter.ofPattern("yyyy/MM").format(LocalDate.now());

        File parentFile=new File(uploadBaseDir,yearAndMonth);
        if(!parentFile.exists()){
            parentFile.mkdirs();
        }

        String fileName = System.currentTimeMillis()+"_"+System.nanoTime();
        String originalFilename=imageFile.getOriginalFilename();
        int beginIndex = originalFilename.lastIndexOf(".");
        String suffix= originalFilename.substring(beginIndex);
        String child=fileName+suffix;

        File  dest= new File(parentFile,child);
        try {
            imageFile.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            throw new FileUploadIOException("上传图片失败！服务器忙，请稍后再次尝试！");
        }catch (IllegalStateException e){
            e.printStackTrace();
            throw new FileStateException("上传图片失败！原文件不可用，请检查原文件");
        }
        // 响应
        String url = "http://localhost:8080/" + yearAndMonth + "/" + child;
        System.out.println("url=" + url);
        return Result.ok(url);
    }

    @GetMapping("/most-hits")
    public Result<List<QuestionSimpleListItemVO>> findMostHitQuestion(){
        return Result.ok(questionService.findQuestionList());
    }

    @GetMapping("/my")
    public Result<PageInfo<Question>> getMyQuestions(@AuthenticationPrincipal LoginUserInfo loginUserInfo,Integer page){
        if(page==null||page<1){
            page=1;
        }
        Integer userId = loginUserInfo.getId();
        PageInfo<Question> questionPageInfo=questionService.getQuestionList(userId,page);
        return Result.ok(questionPageInfo);
    }

    @GetMapping("/{id}")
    public Result<Question> getQuestionDetail(@PathVariable Integer id){
        Question question=questionService.getQuestionDetails(id);
        return Result.ok(question);
    }


}
